package com.ruoyi.web.controller.server;

import java.io.UnsupportedEncodingException;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;

import com.github.pagehelper.PageInfo;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.server.domain.ServerRegion;
import com.ruoyi.server.domain.dto.ServerTaskAddDTO;
import com.ruoyi.server.domain.dto.ServerTaskChangeStateDTO;
import com.ruoyi.server.domain.dto.ServerTaskUpdateDTO;
import com.ruoyi.server.domain.vo.ServerTaskUserAccountVO;
import com.ruoyi.server.domain.vo.ServerTaskVO;
import com.ruoyi.server.service.IServerRegionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.server.domain.ServerTask;
import com.ruoyi.server.service.IServerTaskService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 区服任务Controller
 *
 * @author ghostmen
 * @date 2024-10-31
 */
@Validated
@RestController
@RequestMapping("/server/task")
@Api(value = "区服任务", tags = "区服任务接口")
public class ServerTaskController extends BaseController {

    @Autowired
    private IServerTaskService serverTaskService;
    @Autowired
    private IServerRegionService serverRegionService;

    /**
     * 查询区服任务列表
     */
    @PreAuthorize("@ss.hasPermi('server:task:list')")
    @GetMapping("/list")
    @ApiOperation(value = "查询区服任务列表", notes = "传入serverTask")
    public TableDataInfo list(ServerTask serverTask) {
        PageInfo<ServerTaskVO> list = serverTaskService.selectServerTaskList(serverTask);
        return getDataTable(list);
    }

    /**
     * 获取区服任务详细信息
     */
    @PreAuthorize("@ss.hasPermi('server:task:query')")
    @GetMapping(value = "/{taskId}")
    @ApiOperation(value = "获取区服任务详细信息", notes = "传入taskId")
    public AjaxResult getInfo(@PathVariable("taskId") Long taskId) {
        return success(serverTaskService.selectServerTaskByTaskId(taskId));
    }

    /**
     * 导出区服任务详细信息及账号密码
     */
    @PreAuthorize("@ss.hasPermi('server:task:export')")
    @Log(title = "导出区服任务详细信息及账号密码", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, @RequestParam Long taskId) {
        List<ServerTaskUserAccountVO> list = serverTaskService.selectServerTaskAppUserAccountListBy(taskId);
        ExcelUtil<ServerTaskUserAccountVO> util = new ExcelUtil<ServerTaskUserAccountVO>(ServerTaskUserAccountVO.class);
        String name = cleanSheetName(list.get(0).getTaskName());
        util.exportExcel(response, list, name, name);
    }

    public static String cleanSheetName(String sheetName) {
        // 使用合并的正则表达式进行替换
        String cleanedName = sheetName
                .replaceAll("[/\\\\:*?]", "|")   // 替换 \ / : ? * 为 |
                .replaceAll("\\[", "【")          // 替换 [ 为 【
                .replaceAll("\\]", "】");         // 替换 ] 为 】

        // 截取前31个字符，确保长度不超过31
        if (cleanedName.length() > 31) {
            cleanedName = cleanedName.substring(0, 31);
        }
        return cleanedName;
    }

    /**
     * 区服下拉列表
     */
    @PreAuthorize("@ss.hasPermi('server:task:regionList')")
    @GetMapping("/regionList")
    @ApiOperation(value = "区服下拉列表")
    public AjaxResult regionList() {
        List<ServerRegion> list = serverRegionService.selectList();
        return success(list);
    }

    /**
     * 新增区服任务
     */
    @RepeatSubmit
    @PreAuthorize("@ss.hasPermi('server:task:add')")
    @Log(title = "区服任务", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation(value = "新增区服任务", notes = "传入addDTO")
    public AjaxResult add(@Valid @RequestBody ServerTaskAddDTO addDTO) {
        addDTO.setLoginUser(getLoginUser());
        return toAjax(serverTaskService.insertServerTask(addDTO));
    }

    /**
     * 修改区服任务
     */
    @PreAuthorize("@ss.hasPermi('server:task:edit')")
    @Log(title = "区服任务", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation(value = "修改区服任务", notes = "传入updateDTO")
    public AjaxResult edit(@Valid @RequestBody ServerTaskUpdateDTO updateDTO) {
        updateDTO.setLoginUser(getLoginUser());
        return toAjax(serverTaskService.updateServerTask(updateDTO));
    }

    /**
     * 变更区服任务状态
     */
    @RepeatSubmit
    @PreAuthorize("@ss.hasPermi('server:task:changeState')")
    @Log(title = "区服任务", businessType = BusinessType.UPDATE)
    @PostMapping("/changeState")
    @ApiOperation(value = "变更区服任务状态", notes = "传入updateDTO")
    public AjaxResult changeState(@Valid @RequestBody ServerTaskChangeStateDTO changeStateDTO) {
        changeStateDTO.setLoginUser(getLoginUser());
        return toAjax(serverTaskService.changeState(changeStateDTO));
    }

    /**
     * 删除区服任务
     */
    @PreAuthorize("@ss.hasPermi('server:task:remove')")
    @Log(title = "区服任务", businessType = BusinessType.DELETE)
    @DeleteMapping("/{taskIds}")
    @ApiOperation(value = "删除区服任务", notes = "传入taskIds")
    public AjaxResult remove(@PathVariable Long[] taskIds) {
        return toAjax(serverTaskService.deleteServerTaskByTaskIds(taskIds));
    }

}
